package com.thread;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @author: mayu
 * @date: 2021年04月09日 11:36
 */
public class TestWithLockSupprotWithoutSleep {
    //volatile List lists = new ArrayList<>();
    volatile List lists = Collections.synchronizedList(new ArrayList<>());

    void add(Object o) {
        lists.add(o);
    }

    int size() {
        return lists.size();
    }

    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {
        TestWithLockSupprotWithoutSleep twlsws = new TestWithLockSupprotWithoutSleep();

        //t2相当于监视线程
        t2 = new Thread(() -> {
            System.out.println("t2启动");
            //if (twlsws.lists.size() != 5) {
                LockSupport.park();
            //}
            System.out.println("t2结束");
            LockSupport.unpark(t1);
        }, "t2");

        //try {
        //    TimeUnit.SECONDS.sleep(1);
        //} catch (InterruptedException e) {
        //    e.printStackTrace();
        //}

        t1 = new Thread(() -> {
            System.out.println("t1启动");
            for (int i = 0; i < 10; i++) {
                twlsws.add(i);
                System.out.println(i);
                if (twlsws.lists.size() == 5) {
                    LockSupport.unpark(t2);
                    LockSupport.park(t1);
                }
                //try {
                //    TimeUnit.SECONDS.sleep(1);
                //} catch (InterruptedException e) {
                //    e.printStackTrace();
                //}
            }
            System.out.println("t1结束");
        }, "t1");

        t2.start();
        t1.start();

    }
}
